<template>
  <div>
    <el-dialog
      :title="dialogName == '编辑权限组' ? dialogName + '-' + ruleForm.name : dialogName"
      :visible.sync="dialogVisible"
      width="70%"
    >
      <el-steps :active="active_bz" finish-status="success" simple style="margin: 20px 0">
        <el-step title="权限组设置"></el-step>
        <el-step title="选择人员"></el-step>
        <el-step title="选择设备"></el-step>
      </el-steps>
      <!-- 权限组设置 -->
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="auto" v-show="active_bz == 1">
        <el-form-item label="权限组名称" prop="name">
          <el-input v-model="ruleForm.name" style="width: 50%"></el-input>
        </el-form-item>
        <!-- <el-form-item label="权限组有效期" prop="perid_status">
          <el-radio-group v-model="ruleForm.perid_status">
            <el-radio :label="0">永久</el-radio>
            <el-radio :label="1">临时</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="" prop="perid" v-if="ruleForm.perid_status == 1">
          <el-date-picker
            v-model="ruleForm.perid"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item> -->

        <el-form-item label="是否关联公寓" prop="gy_status">
          <el-radio-group v-model="ruleForm.gy_status">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="园区" prop="community_id" v-if="ruleForm.gy_status == 1">
          <el-select v-model="ruleForm.community_id" placeholder="请选择园区" @change="changeyq">
            <el-option
              :label="item.name"
              :value="item.community_id"
              v-for="(item, index) in shoolList"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="楼撞" prop="building_id" v-if="ruleForm.gy_status == 1">
          <el-select v-model="ruleForm.building_id" placeholder="请选择楼撞" multiple collapse-tags>
            <el-option
              :label="item.name"
              :value="item.building_id"
              v-for="(item, index) in ldList"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 已选择人员 -->
      <div v-show="active_bz == 2">
        <el-row :gutter="20" style="margin-bottom: 10px">
          <el-col :span="5">
            <el-input v-model="formData_tc1.name" clearable placeholder="请输入人员姓名"></el-input>
          </el-col>
          <el-col :span="5">
            <el-input v-model="formData_tc1.mobile" clearable placeholder="请输入人员手机号"></el-input>
          </el-col>
          <el-col :span="4">
            <el-input v-model="formData_tc1.no" clearable placeholder="请输入学工号"></el-input>
          </el-col>
          <el-col :span="4">
            <el-select style="width: 100%" v-model="formData_tc1.type" clearable placeholder="请选择">
              <el-option
                v-for="item in tc2options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <div class="btn">
              <el-button type="primary" @click="tc1serarch">查询</el-button>
              <el-button @click="tc1cz">重置</el-button>
              <el-button type="warning" @click="plsc">批量删除</el-button>
              <el-button type="primary" plain @click="openRY">选择人员</el-button>
            </div>
          </el-col>
        </el-row>
        <div class="table-tc1">
          <div class="tcl-querytable">
            <QueryTable
              :tableConfiguration="tableConfiguration_tc1"
              :displayContent="displayContent_tc1"
              :formData="formData_tc1"
              ref="queryTable_tc1"
              :isPop="true"
              :api="getTableServe_tc1"
              @multipleChoices="deleteChoices"
            >
              <template v-slot:type="{ scope }">
                {{ scope.row.type == 1 ? '学生' : scope.row.type == 2 ? '临时人员' : '未知类型' }}
              </template>
              <template v-slot:room_name="{ scope }">
                {{ scope.row.community_name }}{{ scope.row.building_name }}{{ scope.row.room_name }}
              </template>
              <template v-slot:btn="{ scope }">
                <el-button type="text" style="color: red" @click="peopledelete(scope.row, '单选')">删除</el-button>
              </template>
            </QueryTable>
          </div>
          <div class="tcl-people-list" v-if="peopleList.length > 0">
            <div>已选择人员：</div>
            <el-tag v-for="(tag, index) in peopleList" :key="tag.no">
              {{ tag.name }}
            </el-tag>
          </div>
        </div>
      </div>

      <!-- 选择人员  -->
      <el-dialog width="70%" title="选择人员" :visible.sync="innerVisible" append-to-body>
        <el-row :gutter="20">
          <el-col :span="5">
            <el-input v-model="formData_tc2.name" clearable placeholder="请输入人员姓名"></el-input>
          </el-col>
          <el-col :span="5">
            <el-input v-model="formData_tc2.no" clearable placeholder="请输入学工号"></el-input>
          </el-col>
          <el-col :span="5">
            <el-input v-model="formData_tc2.mobile" clearable placeholder="请输入人员手机号"></el-input>
          </el-col>
          <el-col :span="5">
            <el-select v-model="formData_tc2.type" clearable placeholder="请选择人员类型">
              <el-option
                v-for="item in tc2options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="4">
            <div class="btn">
              <el-button type="primary" @click="tc2serarch">查询</el-button>
              <el-button @click="tc2cz">重置</el-button>
            </div>
          </el-col>
        </el-row>
        <div class="pelople-box">
          <div class="people-table" v-if="innerVisible">
            <QueryTable
              :tableConfiguration="tableConfiguration_tc2"
              :displayContent="displayContent_tc2"
              :formData="formData_tc2"
              ref="queryTable_tc2"
              :isPop="true"
              :api="getTableServe_tc2"
              @multipleChoices="multipleChoices"
            >
              <template v-slot:avatar="{ scope }">
                <el-image
                  style="width: 50px; height: 50px"
                  :src="scope.row.avatar"
                  :preview-src-list="[scope.row.avatar]"
                ></el-image>
              </template>
              <template v-slot:type="{ scope }">
                {{ scope.row.type == 1 ? '学生' : scope.row.type == 2 ? '临时人员' : '未知类型' }}
              </template>
              <template v-slot:btn="{ scope }">
                <el-button type="text">删除</el-button>
              </template>
            </QueryTable>
          </div>
          <div class="people-list">
            <el-tag v-for="(tag, index) in peopleList" :key="tag.no">
              {{ tag.name }}
            </el-tag>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeTC">取 消</el-button>
          <el-button type="primary" @click="sureTC">确定</el-button>
        </span>
      </el-dialog>

      <!-- 已选择设备 -->
      <div v-show="active_bz == 3">
        <el-row :gutter="20" style="margin-bottom: 10px">
          <el-col :span="5">
            <el-input v-model="formData_tc3.name" clearable placeholder="请输入设备名称"></el-input>
          </el-col>
          <el-col :span="5">
            <el-input v-model="formData_tc3.location" clearable placeholder="请输入设备位置"></el-input>
          </el-col>
          <el-col :span="5">
            <el-select
              style="width: 100%"
              v-model="formData_tc3.status"
              clearable
              placeholder="请选择设备在线状态"
            >
              <el-option
                v-for="item in tc3options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-select
              style="width: 100%"
              v-model="formData_tc3.GIDS"
              multiple
              collapse-tags
              clearable
              placeholder="请选择区域"
            >
              <el-option
                v-for="item in tc4options"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="4">
            <div class="btn">
              <el-button type="primary" @click="tc3serarch">查询</el-button>
              <el-button @click="tc3cz">重置</el-button>
            </div>
          </el-col>
        </el-row>
        <QueryTable
          :tableConfiguration="tableConfiguration_tc3"
          :displayContent="displayContent_tc3"
          :formData="formData_tc3"
          ref="queryTable_tc3"
          :isPop="true"
          :api="getTableServe_tc3"
          @multipleChoices="changeSB"
        >
          <template v-slot:avatar="{ scope }">
            <el-image
              style="width: 50px; height: 50px"
              :src="scope.row.avatar"
              :preview-src-list="[scope.row.avatar]"
            ></el-image>
          </template>
          <template v-slot:status="{ scope }">
            <el-tag type="success" v-if="scope.row.status == 1">在线</el-tag>
            <el-tag type="info" v-if="scope.row.status == 2">离线</el-tag>
          </template>
          <template v-slot:btn="{ scope }">
            <el-button type="text">删除</el-button>
          </template>
        </QueryTable>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm('ruleForm')" v-if="active_bz == 1">取 消</el-button>
        <el-button type="info" v-if="active_bz > 1" @click="upSyb">上一步</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')" v-if="active_bz != 3">下一步</el-button>
        <el-button type="primary" v-if="active_bz == 3" @click="sureBtn">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import QueryTable from '@/components/queryTable/index.vue';

import { arealevelfind, sysstudentlist } from '@/api/comment/studentList.js';
import {
  permissiongroupadd,
  permissiongroupedit,
  groupuserlist,
  groupusersdel,
  sysdevicesselect
} from '@/api/comment/permission.js';
import { sysdeviceslist } from '@/api/comment/EquipmentList.js';

export default {
  components: {
    QueryTable
  },

  data() {
    return {
      //弹框
      dialogVisible: false,
      dialogName: '', //弹框名称
      shoolList: [], //学校列表
      ldList: [], //楼栋列表
      ruleForm: {},
      rules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        perid_status: [{ required: true, message: '请选择权限组有效期', trigger: 'change' }],
        perid: [{ required: true, message: '请选择时间', trigger: 'change' }],
        gy_status: [{ required: true, message: '请选择是否关联公寓', trigger: 'change' }],
        community_id: [{ required: true, message: '请选择园区', trigger: 'change' }]
      },

      // 步骤条
      active_bz: 1,
      getTableServe_tc1: groupuserlist,
      displayContent_tc1: {
        height: '40vh',
        indexFixed: true,
        selectionFixed: true,
        selection: true,
        index: true,
        paginationShow: true,
        rowKey: 'no' //用来回显多选或者其他
      },
      formData_tc1: {
        is_select: true //true表示查询已选的，false表示查询未选的
      }, //传给后端的参数
      tableConfiguration_tc1: [
        {
          prop: 'name',
          label: '姓名',
          width: '260',
          //   showOverflowTooltip: true,
          align: 'center'
        },

        {
          prop: 'no',
          label: '学/工号',
          width: '260',
          align: 'center'
        },
        {
          prop: 'mobile',
          label: '联系方式',
          width: '260',
          align: 'center'
        },
        {
          prop: 'type',
          label: '人员类型',
          width: '160',
          align: 'center',
          sockets: true
        },
        {
          prop: 'room_name',
          label: '宿舍',
          width: '260',
          align: 'center',
          sockets: true
        },
        {
          prop: 'merge_name',
          label: '部门',
          width: '260',
          align: 'center'
        },
        {
          label: '操作',
          prop: 'btn',
          width: '100px',
          align: 'center',
          fixed: 'right',
          sockets: true
        }
      ],

      //选择人员弹窗
      innerVisible: false,
      getTableServe_tc2: groupuserlist,
      displayContent_tc2: {
        height: '40vh',
        indexFixed: false,
        selectionFixed: true,
        selection: true,
        index: true,
        paginationShow: true,
        rowKey: 'no', //用来回显多选或者其他
        reserveSelection: true //是否固化选择
      },
      formData_tc2: {}, //传给后端的参数
      tableConfiguration_tc2: [
        {
          prop: 'name',
          label: '姓名',
          width: '260',
          //   showOverflowTooltip: true,
          align: 'center'
        },
        {
          prop: 'no',
          label: '学/工号',
          width: '260',
          align: 'center'
        },

        {
          prop: 'type',
          label: '人员类型',
          width: '260',
          align: 'center',
          sockets: true
        },
        {
          prop: 'mobile',
          label: '联系方式',
          width: '260',
          align: 'center'
        },
        {
          prop: 'merge_name',
          label: '部门',
          width: '260',
          align: 'center'
        }
      ],
      peopleList: [], //已选择人员弹窗
      tc2options: [
        {
          value: 1,
          label: '学生'
        },
        {
          value: 2,
          label: '临时人员'
        }
      ],
      tcjg: [], //机构

      //选择设备
      getTableServe_tc3: sysdeviceslist,
      displayContent_tc3: {
        height: '40vh',
        indexFixed: false,
        selectionFixed: true,
        selection: true,
        index: true,
        paginationShow: true,
        rowKey: 'ldid', //用来回显多选或者其他
        reserveSelection: true //是否固化选择
      },
      formData_tc3: {}, //传给后端的参数
      tableConfiguration_tc3: [
        {
          prop: 'name',
          label: '设备名称',
          width: '260',
          //   showOverflowTooltip: true,
          align: 'center'
        },
        {
          prop: 'serialNumber',
          label: '设备编号',
          width: '260',
          align: 'center'
        },
        {
          prop: 'location',
          label: '设备位置',
          width: '260',
          align: 'center'
        },
        {
          prop: 'status',
          label: '设备状态',
          width: '260',
          align: 'center',
          sockets: true
        }
      ],
      tc3options: [
        {
          value: 1,
          label: '在线'
        },
        {
          value: 2,
          label: '离线'
        }
      ],
      tc4options: [],

      myNO: [] //多选删除
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    this.getarealevelfind({ level: 0 }, '园区');
    this.getsyspartyorganize();
    this.getsysdevicesselect(); //获取校区
  },
  methods: {
    //添加编辑权限组
    open(name, data) {
      this.dialogName = name;

      this.active_bz = 1;
      this.dialogVisible = true;
      this.peopleList = [];

      this.formData_tc2 = {}; //清空查询
      this.formData_tc3 = {}; //清空查询

      if (name == '编辑权限组') {
        this.ruleForm = { ...data };

        this.formData_tc1._id = this.ruleForm._id;
        this.formData_tc2._id = this.ruleForm._id;

        //有在调用
        if (this.ruleForm.community_id) {
          this.getarealevelfind({ level: 1, value: this.ruleForm.community_id }, '楼撞');
        }

        this.$nextTick(() => {
          this.$refs.queryTable_tc3.showSelectionChange(this.ruleForm.devices, 'ldid');
        });
      } else {
        this.formData_tc1._id = '';

        this.ruleForm = {};
        this.$nextTick(() => {
          this.$refs.queryTable_tc3.showSelectionChange([], 'ldid'); //清除多选
        });
      }

      //调用接口
      this.$nextTick(() => {
        this.$refs.queryTable_tc1.handleCurrentChange(1);

        //处理GIDS
        if (this.formData_tc3.GIDS && this.formData_tc3.GIDS.length == 0) {
          delete this.formData_tc3.GIDS;
        }
        this.formData_tc3.core = true;
        this.$refs.queryTable_tc3.handleCurrentChange(1);
      });
    },

    //上一步
    upSyb() {
      this.active_bz--;
    },

    //下一步
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.active_bz++;
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    //确定按钮
    sureBtn() {
      if (this.dialogName == '添加权限组') {
        this.addData();
      } else {
        this.editData();
      }
    },

    //新增权限组
    async addData() {
      try {
        let res = await permissiongroupadd(this.ruleForm);
        if (res.code == 0) {
          this.$message({
            message: '添加成功',
            type: 'success'
          });

          this.$emit('czData');
          this.resetForm('ruleForm');
        } else {
          this.$message.error(res.msg);
        }
      } catch (error) {
        this.$message.error('添加失败');
      }
    },

    //编辑权限组
    async editData() {
      try {
        let res = await permissiongroupedit(this.ruleForm);
        if (res.code == 0) {
          this.$message({
            message: '添加成功',
            type: 'success'
          });
          this.$emit('czData');
          this.resetForm('ruleForm');
        }
      } catch (error) {
        this.$message.error('添加失败');
      }
    },

    //清空校验
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogVisible = false;
    },
    //选中园区
    changeyq(e) {
      this.getarealevelfind({ level: 1, value: e }, '楼撞');
      this.$set(this.ruleForm, 'building_id', '');
    },

    //删除中人员(多选)
    deleteChoices(e) {
      console.log(e);

      this.myNO = e.map((item) => item.no);
    },

    //批量删除
    plsc() {
      if (this.myNO.length == 0) {
        return this.$message({
          type: 'warning',
          message: '请选择人员'
        });
      }
      this.peopledelete(this.myNO, '多选');
    },

    //删除人员
    peopledelete(e, name) {
      let nos = [];
      if (name == '单选') {
        nos.push(e.no);
      } else {
        nos = e;
      }
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let res = await groupusersdel({ groupId: this.ruleForm.groupId, nos: nos });
          if (res.code == 0) {
            this.$message({
              type: 'success',
              message: '删除成功'
            });

            this.$nextTick(() => {
              this.$refs.queryTable_tc1.handleCurrentChange(1);
            });
          } else {
            this.$message({
              type: 'error',
              message: '删除失败！'
            });
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '删除失败！'
          });
        });
    },

    //打开选择人员弹窗
    openRY() {
      this.innerVisible = true;

      this.$nextTick(() => {
        this.$refs.queryTable_tc2.handleCurrentChange(1);

        if (this.peopleList.length > 0) {
          this.$refs.queryTable_tc2.showSelectionChange(
            this.peopleList.map((item) => item.no),
            'no'
          );
        }
      });
    },

    //选择人员多选
    multipleChoices(e) {
      let myuser = e.map((item) => item.no);

      if (this.ruleForm.users && this.ruleForm.users.length > 0) {
        this.ruleForm.users = [...this.ruleForm.users, ...myuser];
      } else {
        this.ruleForm.users = myuser;
      }
      // console.log(this.ruleForm);
      this.peopleList = e; //展示标签
    },

    //关闭选择人员弹窗
    closeTC() {
      this.innerVisible = false;
      this.peopleList = [];
    },

    //确定弹窗
    sureTC() {
      this.innerVisible = false; //关闭选择弹窗
    },

    //已选择人员列表查询
    tc1serarch() {
      this.$nextTick(() => {
        this.$refs.queryTable_tc1.handleCurrentChange(1);
      });
    },
    tc1cz() {
      this.$set(this.formData_tc1, 'name', '');
      this.$set(this.formData_tc1, 'mobile', '');
      this.$set(this.formData_tc1, 'no', '');

      this.$nextTick(() => {
        this.$refs.queryTable_tc1.handleCurrentChange(1);
      });
    },

    //选择人员查询
    tc2serarch() {
      this.$nextTick(() => {
        this.$refs.queryTable_tc2.handleCurrentChange(1);
      });
    },
    //选择人员重置
    tc2cz() {
      this.$set(this.formData_tc2, 'name', '');
      this.$set(this.formData_tc2, 'type', '');
      this.$set(this.formData_tc2, 'no', '');

      this.$nextTick(() => {
        this.$refs.queryTable_tc2.handleCurrentChange(1);
      });
    },

    //选择设备查询
    tc3serarch() {
      this.$nextTick(() => {
        //处理GIDS
        if (this.formData_tc3.GIDS && this.formData_tc3.GIDS.length == 0) {
          delete this.formData_tc3.GIDS;
        }
        this.$refs.queryTable_tc3.handleCurrentChange(1);
      });
    },
    //选择人员重置
    tc3cz() {
      this.formData_tc3 = {
        core: true
      };
      this.$nextTick(() => {
        this.$refs.queryTable_tc3.handleCurrentChange(1);
      });
    },

    //选择设备
    changeSB(e) {
      console.log(e);
      this.ruleForm.devices = e.map((item) => item.ldid);
    },

    //获取--校区/楼栋/楼层/房屋
    async getarealevelfind(val, name) {
      try {
        let res = await arealevelfind(val);
        if (res.code == 0) {
          if (name == '园区') {
            this.shoolList = res.data;
          } else {
            this.ldList = res.data;
          }
        }
      } catch (error) {}
    },

    //获取机构
    async getsyspartyorganize() {
      try {
        let res = await syspartyorganize();
        if (res.code == 0) {
          this.tcjg = res.data;
        }
      } catch (error) {}
    },

    //获取校区
    async getsysdevicesselect() {
      let res = await sysdevicesselect();
      console.log(res, '校区');
      if (res.code == 0) {
        this.tc4options = res.data;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.pelople-box {
  width: 100%;
  display: flex;
  gap: 0 10px;
  margin-top: 10px;

  .people-table {
    width: 75%;
  }

  .people-list {
    width: 34%;
    height: 40vh;
    overflow-y: auto;
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    gap: 10px;
  }
}

.table-tc1 {
  display: flex;
  gap: 0 10px;
  .tcl-querytable {
    width: 75%;
  }

  .tcl-people-list {
    width: 34%;
    height: 40vh;
    overflow-y: auto;
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    gap: 10px;
  }
}

.btn {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
</style>
